package es.usj;

import java.util.Date;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import android.util.Log;

public class ReceptorBroadcast extends BroadcastReceiver
{
      
    @Override
    public void onReceive(Context context, Intent intent)
    {
/*		PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
		PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
		wl.acquire();*/
		Bundle data = intent.getExtras();
		if (data != null) {
			long fechaMs = data.getLong("fecha", 0);
			int minutos = data.getInt("minutos", 0);
			int horas = data.getInt("horas", 0);
			String descripcion = data.getString("descripcion");
			boolean repetir = data.getBoolean("repetir", false);
			if (descripcion != null && fechaMs > 0)
				Log.w("ReceptorBroadcast", "recibidos parametros: fechaMs="+new Date(fechaMs).toString() + " descripcion=" + descripcion);
		}

		Intent servicio = new Intent(context, ServicioAlarmas.class);
		context.startService(servicio);
		Toast.makeText(context, "Notificacion de alarma seleccionada!", Toast.LENGTH_LONG).show();
//        wl.release();
       
    } 

    /**
     * Establece alarma
     * @param contexto contexto
     * @param fechaActual fecha
     * @param repetir milisegundos para repetir.
     */
	public void SetAlarm(Context contexto, Date fechaAlarma, long repetir)
	{
		long currentTime = 0;
	    AlarmManager am = (AlarmManager) contexto.getSystemService(Context.ALARM_SERVICE);
	    Intent i = new Intent(contexto, ServicioAlarmas.class);
	    PendingIntent pi = PendingIntent.getBroadcast(contexto, 0, i, 0);
	    if (fechaAlarma == null) {
	    	currentTime = System.currentTimeMillis();
	    } else {
	    	currentTime = fechaAlarma.getTime();
	    }
	    if (repetir > 0) {
		    am.setInexactRepeating(AlarmManager.RTC_WAKEUP, currentTime, repetir, pi); // Millisec * Second * Minute
	    } else {
		    am.set(AlarmManager.RTC_WAKEUP, currentTime, pi);
	    }
	}
	
	public void CancelAlarm(Context context)
	{
	    Intent intent = new Intent(context, ServicioAlarmas.class);
	    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
	    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
	    alarmManager.cancel(sender);
	}
}